package com.yunchang.springboot.scheduled.caravanapi;

import com.alibaba.fastjson.JSONArray;
import com.yunchang.springboot.base.BaseService;
import com.yunchang.springboot.mapper.base.FinanceShopSkuMapper;
import com.yunchang.springboot.mapper.basic.IBaseErpskuSkuRelationMapper;
import com.yunchang.springboot.mapper.basic.IBaseSkuInfoMapper;
import com.yunchang.springboot.mapper.caravan.*;
import com.yunchang.springboot.mapper.caravan.CaravanMskuShippbatchDataMapper;
import com.yunchang.springboot.models.DO.*;
import com.yunchang.springboot.models.DO.basic.BaseErpskuSkuRelationDTO;
import com.yunchang.springboot.models.DO.basic.BaseSkuInfoDTO;
import com.yunchang.springboot.models.DataGetErrorRecord;
import com.yunchang.springboot.models.base.FinanceShopSku;
import com.yunchang.springboot.utils.DateUtil;
import com.yunchang.springboot.utils.StringUtil;
import com.yunchang.springboot.utils.ToolUtil;
import com.yunchang.springboot.utils.caravan.CaravanApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 马帮api定时任务
 *
 * @author wanglongwei
 * @data 2019/9/2 16:15
 */
@Component
@Configuration
@Service
@Slf4j
//@EnableScheduling
public class CaravanApiSchedule extends BaseService {

    @Autowired
    CaravanMskuShippbatchDataMapper mskuShippbatchDataMapper;

    @Autowired
    CaravanStockWarehouseDataMapper stockWarehouseDataMapper;

    @Autowired
    CaravanPurchaseDataMapper purchaseDataMapper;

    @Autowired
    CaravanMskuDataMapper mskuDataMapper;

    @Autowired
    CaravanOrderDataMapper orderDataMapper;

    @Autowired
    CaravanBillsDataMapper billsDataMapper;

    @Autowired
    CaravanAccountDataMapper accountDataMapper;

    @Autowired
    CaravanStorageLogDataMapper storageLogDataMapper;

    @Autowired
    CaravanStockDataMapper stockDataMapper;

    @Autowired
    CaravanMskuShipDataMapper mskuShipDataMapper;

    @Autowired
    CaravanMskuShippbatchDataPackItemMapper mskuShippbatchDataPackItemMapper;

    @Autowired
    IBaseErpskuSkuRelationMapper iBaseErpskuSkuRelationMapper;

    @Autowired
    FinanceShopSkuMapper financeShopSkuMapper;

    @Autowired
    IBaseSkuInfoMapper iBaseSkuInfoMapper;

    /**
     * 将api出错信息插入数据库
     *
     * @param taskName
     * @param errorMsg
     */
    private void handleErrorSchedule(String taskName, StringBuffer errorMsg) {
        DataGetErrorRecord record = new DataGetErrorRecord();
        record.setShop("马帮api");
        record.setArea("马帮api");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(date);
        record.setDate(format1);
        //是否处理，0:未处理,1:已处理',
        record.setIsHandle(0);
        //类型:马帮api定时任务
        record.setType(3);
        record.setName(taskName);
        record.setRemark("马帮api定时任务，出错时间：" + format1 + ",出错详情:" + errorMsg);
        record.setCreateTime(DateUtil.getFutureDateTime(0));
        baseInsert(record);
    }

    /**
     * 通用逻辑处理
     *
     * @param taskName
     */
    //@Transactional(rollbackFor = Exception.class)
    public void baseHandle(String taskName, String startTime, String endTime) {
        log.info("************马帮api********" + taskName + "在" + startTime + "到" + endTime + "定时任务开始******************");
        //最大出错次数
        int errorMaxNum = 3;
        StringBuffer errMsg = new StringBuffer();
        //昨天的日期
        String lastDate = DateUtil.getFetureDate(-1);
        for (int i = 0; i < errorMaxNum; i++) {
            try {
                //数据是否处理成功
                boolean handleSuccess = false;
                switch (taskName) {
                    case "调拨发货": {
                        handleSuccess = baseHandleGetDate("msku-shippbatch-data", taskName, startTime, endTime);
                    }
                    break;
                    case "商品查询": {
                        //清除昨天的数据
                        //stockWarehouseDataMapper.deleteByDate(lastDate);
                        handleSuccess = baseHandleGetDate("stock-data", taskName, startTime, endTime);
                    }
                    break;
                    case "库存查询": {
                        //清除昨天的数据
                        //stockWarehouseDataMapper.deleteByDate(lastDate);
                        handleSuccess = baseHandleGetDate("stock-warehouse-data", taskName, startTime, endTime);
                    }
                    break;
                    case "采购单": {
                        //清除昨天的数据
//                        purchaseMapper.deleteByDate(lastDate);
                        handleSuccess = baseHandleGetDate("purchase-data", taskName, startTime, endTime);
                    }
                    break;
                    case "出入库流水": {
                        handleSuccess = baseHandleGetDate("storage-log-data", taskName, startTime, endTime);
                    }
                    break;
                    case "收付款单": {
                        handleSuccess = baseHandleGetDate("bills-data", taskName, startTime, endTime);
                    }
                    break;
                    case "MSKU列表": {
                        //清除昨天的数据
//                        mskuMapper.deleteByDate(lastDate);
                        handleSuccess = baseHandleGetDate("msku-data", taskName, startTime, endTime);
                    }
                    break;
                    case "账户日志": {
                        handleSuccess = baseHandleGetDate("account-data", taskName, startTime, endTime);
                    }
                    break;
                    case "补货计划": {
                        handleSuccess = baseHandleGetDate("msku-ship-data", taskName, startTime, endTime);
                    }
                    break;
                    case "订单列表": {
                        handleSuccess = baseHandleGetDate("order-data", taskName, startTime, endTime);
                    }
                    break;
                    default: {
                    }
                }
                //数据处理成功，本地定时任务结束
                if (handleSuccess) {
                    log.info("************马帮api********" + taskName + "在" + startTime + "到" + endTime + "定时任务结束******************");
                    return;
                }
                errMsg.append("第").append(i + 1).append("次，数据获取失败，详情请看日志信息");
            } catch (Exception e) {
                //debug打印错误详情
                log.debug("马帮api，" + taskName + "错误，详情:", e);
                log.warn("马帮api，" + taskName + "错误，详情:" + e);
                errMsg.append("第").append(i + 1).append("次，数据获取失败，详情:").append(e);
            }
        }
        handleErrorSchedule(taskName, errMsg);
        //定时任务出错
        log.error(errMsg.toString());
        log.info("************马帮api********" + taskName + "在" + startTime + "到" + endTime + "定时任务结束******************");
    }

    /**
     * 通用逻辑处理
     *
     * @param moduleParam
     * @param type
     * @return
     * @throws Exception
     */
    public boolean baseHandleGetDate(String moduleParam, String type, String startTime, String endTime) throws Exception {
        //调一遍接口获取一共有多少数据
        Map<String, Object> module = CaravanApiUtil.getClient(new HashMap<String, String>(2) {{
            put("module", moduleParam);
            put("page", "1");
            put("updateTimeStart", startTime);
            put("updateTimeEnd", endTime);
        }});

        //null代表获取数据失败，详情查看控制台
        if (null == module) {
            log.warn("马帮api获取出错");
            return false;
        }

        int pageCount = ToolUtil.valueOfInteger(StringUtil.valueOf(module.get("pageCount")));
        //错误次数
        int errorNum = 0;
        for (int i = 1; i <= pageCount; i++) {
            //延迟一秒
            Thread.sleep(2L);
            String page = String.valueOf(i);
            Map<String, Object> client = CaravanApiUtil.getClient(new HashMap<String, String>(2) {{
                put("module", moduleParam);
                put("page", page);
                put("updateTimeStart", startTime);
                put("updateTimeEnd", endTime);
            }});
            if (null == client) {
                errorNum++;
                //如果错误次数超过3次，本次处理数据失败
                if (errorNum > 3) {
                    return false;
                }
                //重新获取数据
                i -= 1;
                continue;
            }
            List<Map> data = JSONArray.parseArray(StringUtil.valueOf(client.get("data")), Map.class);
            switch (type) {
                case "账户日志": {
                    handleAccountData(data);
                }
                break;
                case "收付款单": {
                    //需要更新数据
                    handleBillsData(data);
                }
                break;
                case "MSKU列表": {
                    handleMskuData(data);
                }
                break;
                case "补货计划": {
                    handleMskuShipData(data);
                }
                break;
                case "调拨发货": {
                    handleMskuShippbatchData(data);
                }
                break;
                case "订单列表": {
                    handleOrderData(data);
                }
                break;
                case "采购单": {
                    //需要更新数据
                    handlePurchaseData(data);
                }
                break;
                case "商品查询": {
                    //需要更新数据
                    handleStock(data);
                }
                break;
                case "库存查询": {
                    handleStockWarehouseData(data);
                }
                break;
                case "出入库流水": {
                    //直接新增
                    handleStorageLogData(data);
                }
                break;
                default: {
                    log.warn("马帮api没有对应类型，类型:" + type);
                    //没有对应类型
                    return false;
                }
            }
        }
        return true;
    }


    /**
     * 账户日志
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 1 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void accountData() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = accountDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮accountData数据拉取任务");
        baseHandle("账户日志", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理账户日志
     *
     * @param lists
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleAccountData(List<Map> lists) {
        List<CaravanAccountData> insertList = new ArrayList<>(lists.size());
        String futureDate = DateUtil.getFetureDate(0);
        for (Map row : lists) {
            CaravanAccountData data = new CaravanAccountData();
            data.setDate(futureDate);
            String accountId = StringUtil.valueOf(row.get("accountId"));
            String orderId = StringUtil.valueOf(row.get("orderId"));
            String modifyTime = StringUtil.valueOf(row.get("modifyTime"));
            data.setCompanyId(StringUtil.valueOf(row.get("companyId")));
            data.setAccountId(accountId);
            data.setAccountName(StringUtil.valueOf(row.get("accountName")));
            data.setRevenueExpenditure(StringUtil.valueOf(row.get("revenueExpenditure")));
            data.setType(StringUtil.valueOf(row.get("type")));
            data.setOrderId(orderId);
            data.setVariable(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(row.get("variable")))));
            data.setBalance(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(row.get("balance")))));
            data.setCurrency(StringUtil.valueOf(row.get("currency")));
            data.setCreaterId(StringUtil.valueOf(row.get("createrId")));
            data.setCreaterName(StringUtil.valueOf(row.get("createrName")));
            data.setConfirmorId(StringUtil.valueOf(row.get("confirmorId")));
            data.setConfirmorName(StringUtil.valueOf(row.get("confirmorName")));
            data.setModifyTime(modifyTime);
            data.setComment(StringUtil.valueOf(row.get("comment")));
            data.setCreateDataTime(StringUtil.valueOf(row.get("createDataTime")));
//            CaravanAccountData accountDataOneInfo = accountDataMapper.getOneInfoByAccountIdAndOrderIdAndModifyTime(accountId, orderId, modifyTime);
//            if (null != accountDataOneInfo && null != accountDataOneInfo.getId()) {
//                data.setId(accountDataOneInfo.getId());
//                baseUpdate(data);
//            } else {
            //应该还要加上当前日期是否有新数据的判断
            data.setId(null);
//            insertList.add(data);
            accountDataMapper.insert(data);
//            }
        }
//        accountDataMapper.insertList(insertList);
        //baseInsertList(insertList);
    }

    /**
     * 收付款单
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 05 00 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void billsData() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = billsDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮billsData数据拉取任务");
        baseHandle("收付款单", startTime.format(df), endTime.format(df));
    }


    /**
     * 处理收付款单
     *
     * @param lists
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void handleBillsData(List<Map> lists) throws Exception {
        List<CaravanBillsData> insertList = new ArrayList<>(lists.size());
        String fetureDate = DateUtil.getFetureDate(0);
        for (Map row : lists) {
            CaravanBillsData data = new CaravanBillsData();
            String payMentOrderId = StringUtil.valueOf(row.get("payMentOrderId"));
            String orderNum = StringUtil.valueOf(row.get("orderNum"));
            String payTime = StringUtil.valueOf(row.get("payTime"));
            data.setDate(fetureDate);
            data.setCompanyId(StringUtil.valueOf(row.get("companyId")));
            data.setPaymentOrderId(payMentOrderId);
            data.setOrderNum(orderNum);
            data.setAli1688OrderId(StringUtil.valueOf(row.get("ali1688OrderId")));
            data.setAccountId(StringUtil.valueOf(row.get("accountId")));
            data.setAccountName(StringUtil.valueOf(row.get("accountName")));
            data.setOrderType(StringUtil.valueOf(row.get("orderType")));
            data.setCurrency(StringUtil.valueOf(row.get("currency")));
            data.setPaymentTerm(StringUtil.valueOf(row.get("paymentTerm")));
            data.setPaymentTermId(StringUtil.valueOf(row.get("paymentTermId")));
            data.setPaymentTermDesc(StringUtil.valueOf(row.get("paymentTermDesc")));
            data.setPaymentSupplierId(StringUtil.valueOf(row.get("paymentSupplierId")));
            data.setPaymentSupplierName(StringUtil.valueOf(row.get("paymentSupplierName")));
            data.setTotalAmount(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(row.get("totalAmount")))));
            data.setAmount(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(row.get("amount")))));
            data.setStatus(StringUtil.valueOf(row.get("status")));
            data.setPrepayTime(StringUtil.valueOf(row.get("prepayTime")));
            data.setCreaterId(StringUtil.valueOf(row.get("createrId")));
            data.setCreaterName(StringUtil.valueOf(row.get("createrName")));
            data.setCreateTime(StringUtil.valueOf(row.get("createTime")));
            data.setUpdateTime(StringUtil.valueOf(row.get("updateTime")));
            data.setAuditorId(StringUtil.valueOf(row.get("auditorId")));
            data.setAuditor(StringUtil.valueOf(row.get("auditor")));
            data.setPayerId(StringUtil.valueOf(row.get("payerId")));
            data.setPayerName(StringUtil.valueOf(row.get("payerName")));
            data.setPayTime(payTime);
            data.setComment(StringUtil.valueOf(row.get("comment")));
            data.setHandleStatus(0);
            //这张表有更新时间，需要做更新操作
            insertOrUpdateBillsData(orderNum,data);
//            //先判断该账单是否已经存在
//            CaravanBillsData oneInfoCaravanBillsDataDO = billsDataMapper.getOneInfoByOrderNum(orderNum);
//            if (null != oneInfoCaravanBillsDataDO && null != oneInfoCaravanBillsDataDO.getId()) {
//                data.setId(oneInfoCaravanBillsDataDO.getId());
//                baseUpdate(data);
//            } else {
//                data.setId(null);
//                insertList.add(data);
//            }
        }
    }


    /**
     * MSKU列表
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 10 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void msku() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = mskuDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear()-3,1,1,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮mskuData数据拉取任务");
        baseHandle("MSKU列表", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理msku列表
     *
     * @param lists
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void handleMskuData(List<Map> lists) {
        String fetureDate = DateUtil.getFetureDate(0);
        for (Map row : lists) {
            CaravanMskuData mskuData = new CaravanMskuData();
            mskuData.setDate(fetureDate);
            String shops = StringUtil.valueOf(row.get("shops"));
            String msku = StringUtil.valueOf(row.get("msku"));
            String amazonsite = StringUtil.valueOf(row.get("amazonsite"));
            String stockSku = StringUtil.valueOf(row.get("stockSku"));
            mskuData.setCompanyId(StringUtil.valueOf(row.get("companyId")));
            mskuData.setShops(shops);
            mskuData.setShopsName(StringUtil.valueOf(row.get("shopsName")));
            mskuData.setMsku(msku);
            mskuData.setCommodityLinks(StringUtil.valueOf(row.get("commodityLinks")));
            mskuData.setStockId(StringUtil.valueOf(row.get("stockId")));
            mskuData.setStockSku(stockSku);
            mskuData.setAmazonsite(amazonsite);
            mskuData.setGroundingTime(StringUtil.valueOf(row.get("groundingTime")));
            mskuData.setDeveloperId(StringUtil.valueOf(row.get("developerId")));
            mskuData.setDeveloperName(StringUtil.valueOf(row.get("developerName")));
            mskuData.setCreateTime(StringUtil.valueOf(row.get("createTime")));
            mskuData.setUpdateTime(StringUtil.valueOf(row.get("updateTime")));
            mskuData.setStatus(StringUtil.valueOf(row.get("status")));
            mskuData.setStatusDesc(StringUtil.valueOf(row.get("statusdesc")));
            //新增或更新的事务方法
            insertOrUpdateMskuData(shops,msku,amazonsite,mskuData);
//            CaravanMskuData oneInfo = mskuDataMapper.getOneInfoByShopsAndMskuAndAmazonsite(shops, msku, amazonsite);
//            if (null != oneInfo && null != oneInfo.getId()) {
//                mskuData.setId(oneInfo.getId());
//                baseUpdate(mskuData);
//            } else {
//                mskuData.setId(null);
//                baseInsert(mskuData);
//            }

            //根据stockSku去finance_shop_sku表中获得对应的sellerId和area
            FinanceShopSku infoBySku = financeShopSkuMapper.getInfoBySku(stockSku);
            if(infoBySku == null){
                return;
            }
            String sellerId = infoBySku.getSellerId();
            String area = infoBySku.getArea();
            //根据sellerId和area和msku去base_sku_info表中拿到这个msku对应的id
            Integer mskuId = iBaseSkuInfoMapper.getIdByMskuAndSellerIdAndArea(msku, sellerId, area);
            //如果没有这个id，表示这个店铺、这个区域下没有这个msku，新增
            if (mskuId == null){
                mskuId = insertBaseSkuInfo(sellerId,area,msku,fetureDate);
            }
            insertErpSku(mskuId,stockSku,fetureDate);
//            BaseSkuInfoDTO oneInfoBySkuAndErpSku = iBaseErpskuSkuRelationMapper.getOneInfoBySkuAndErpSku(mskuId, stockSku);
//            if (oneInfoBySkuAndErpSku == null){
//                BaseErpskuSkuRelationDTO baseErpskuSkuRelationDTO = new BaseErpskuSkuRelationDTO();
//                baseErpskuSkuRelationDTO.setErpsku(stockSku);
//                baseErpskuSkuRelationDTO.setSku(mskuId);
//                baseErpskuSkuRelationDTO.setAddUser("sujiandong");
//                baseErpskuSkuRelationDTO.setAddTime(fetureDate);
//                baseErpskuSkuRelationDTO.setModUser("sujiandong");
//                baseErpskuSkuRelationDTO.setModTime(fetureDate);
//                iBaseErpskuSkuRelationMapper.insert(baseErpskuSkuRelationDTO);
//            }
        }
//        if (insertList != null && insertList.size() != 0){
//            mskuDataMapper.insertList(insertList);
//        }
        //baseInsertList(insertList);
    }


    /**
     * 补货计划
     * 5分钟
     */
    @Scheduled(cron = "0 15 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void mskuShipData() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = mskuShipDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮mskuShipData数据拉取任务");
        baseHandle("补货计划", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理补货计划
     *
     * @param lists
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleMskuShipData(List<Map> lists) throws Exception {
        List<CaravanMskuShipData> insertList = new ArrayList<>(lists.size());
        String futureDateTime = DateUtil.getFutureDateTime(0);
        for (Map row : lists) {
            CaravanMskuShipData data = new CaravanMskuShipData();
            data.setDate(futureDateTime);
            data.setCompanyId(StringUtil.valueOf(row.get("companyId")));
            data.setFbaStockId(StringUtil.valueOf(row.get("fbaStockId")));
            data.setFbaStockSku(StringUtil.valueOf(row.get("fbaStockSku")));
            data.setApplyQuantity(Integer.parseInt(StringUtil.valueOf(row.get("applyQuantity"))));
            data.setMsku(StringUtil.valueOf(row.get("msku")));
            data.setShopId(StringUtil.valueOf(row.get("shopid")));
            data.setShopName(StringUtil.valueOf(row.get("shopName")));
            data.setAmazonsite(StringUtil.valueOf(row.get("amazonsite")));
            data.setReplenishNum(row.get("replenishNum") != null?Integer.parseInt(StringUtil.valueOf(row.get("replenishNum"))):null);
            data.setTimeCreate(StringUtil.valueOf(row.get("timeCreate")));
            data.setTimeUpdate(StringUtil.valueOf(row.get("timeUpdate")));
            data.setStatus(StringUtil.valueOf(row.get("status")));
            data.setId(null);
            insertList.add(data);
        }
        //baseInsertList(insertList);
        mskuShipDataMapper.insertList(insertList);
    }


    /**
     * 调拨发货
     * 5分钟
     */
    @Scheduled(cron = "0 20 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void allocationAndDelivery() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = mskuShippbatchDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮mskuShippbatchData数据拉取任务");
        baseHandle("调拨发货", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理调拨发货逻辑
     *
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleMskuShippbatchData(List<Map> meterList) {
        for (Map map : meterList) {
            if (map.get("shippNo") == null) {
                break;
            }
            String shippNo = StringUtil.valueOf(map.get("shippNo"));
            //调拨shippNo判断是否添加过
            insertOrUpdateMskuShippbatchData(shippNo,map);

        }
    }


    /**
     * 订单列表
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 25 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void orderData() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = orderDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮orderData数据拉取任务");
        baseHandle("订单列表", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理订单列表
     *
     * @param lists
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleOrderData(List<Map> lists) {
        List<CaravanOrderData> orderDataList = new ArrayList<>();
        List<CaravanOrderDataItem> itemsList = new ArrayList<>();
        String fetureDate = DateUtil.getFetureDate(0);
        for (Map row : lists) {
            CaravanOrderData data = new CaravanOrderData();
            data.setDate(fetureDate);
            data.setCompanyId(StringUtil.valueOf(row.get("companyId")));
            String platformOrderId = StringUtil.valueOf(row.get("platformOrderId"));
            data.setPlatformOrderId(platformOrderId);
            data.setSalesRecordNumber(StringUtil.valueOf(row.get("salesRecordNumber")));
            data.setPaidTime(StringUtil.valueOf(row.get("paidTime")));
            data.setUpdateTime(StringUtil.valueOf(row.get("updateTime")));
            data.setShopId(StringUtil.valueOf(row.get("shopId")));
            data.setShopName(StringUtil.valueOf(row.get("shopName")));
            data.setPlatformId(StringUtil.valueOf(row.get("platformId")));
            data.setPlatformName(StringUtil.valueOf(row.get("platformName")));
            data.setPlatformOrderStatus(StringUtil.valueOf(row.get("platformOrderStatus")));
            data.setOrderStatus(StringUtil.valueOf(row.get("orderStatus")));
            data.setOrderStatusCn(StringUtil.valueOf(row.get("orderStatusCn")));
            data.setItemTotalOrigin(row.get("itemTotalOrigin") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("itemTotalOrigin")))):null);
            data.setOrderTotalOrigin(row.get("orderTotalOrigin") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("orderTotalOrigin")))):null);
            data.setCurrencyRate(row.get("currencyRate") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("currencyRate")))):null);
            data.setCurrencyId(StringUtil.valueOf(row.get("currencyId")));
            data.setOrderWeight(row.get("orderWeight") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("orderWeight")))):null);
            data.setIsReturned(StringUtil.valueOf(row.get("isReturned")));
            data.setExpressTime(StringUtil.valueOf(row.get("expressTime")));
            data.setSkuNum(row.get("skuNum") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("skuNum")))):null);
            data.setRemark(StringUtil.valueOf(row.get("remark")));
            data.setPaypalId(StringUtil.valueOf(row.get("paypalId")));
            data.setOtherExpend(row.get("otherExpend") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("otherExpend")))):null);
            data.setOtherIncome(row.get("otherIncome") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("otherIncome")))):null);
            data.setShippingFee(row.get("shippingFee") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("shippingFee")))):null);
            data.setPlatformFee(row.get("platformFee") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("platformFee")))):null);
            data.setPaypalFee(row.get("paypalFee") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("paypalFee")))):null);
            data.setLogisticsName(StringUtil.valueOf(row.get("logisticsName")));
            data.setLogisticsChannelName(StringUtil.valueOf(row.get("logisticsChannelName")));
            data.setTrackNumber(StringUtil.valueOf(row.get("trackNumber")));
//            CaravanOrderData oneInfoByPlatformOrderId = orderDataMapper.getOneInfoByPlatformOrderId(platformOrderId);
            //Long orderId = null;
//            if (null != oneInfoByPlatformOrderId && null != oneInfoByPlatformOrderId.getId()) {
//                Long id = oneInfoByPlatformOrderId.getId();
//                data.setId(id);
//                baseUpdate(data);
//                orderIds.add(id);
//            } else {
            data.setId(null);
            orderDataList.add(data);
//            }
            //orderId = data.getId();
            if (null == row.get("item")) {
                continue;
            }
            List<Map> items = JSONArray.parseArray(StringUtil.valueOf(row.get("item")), Map.class);
            for (Map item : items) {
                CaravanOrderDataItem dataItem = new CaravanOrderDataItem();
                dataItem.setPlatformOrderId(platformOrderId);
                dataItem.setDate(fetureDate);
                dataItem.setStockSku(StringUtil.valueOf(item.get("stockSku")));
                dataItem.setItemWeight(row.get("itemWeight") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(item.get("itemWeight")))):null);
                dataItem.setItemQuantity(Integer.parseInt(StringUtil.valueOf(item.get("itemQuantity"))));
                dataItem.setPlatformSku(StringUtil.valueOf(item.get("platformSku")));
                dataItem.setPlatformQuantity(row.get("platformQuantity") != null?Integer.parseInt(StringUtil.valueOf(item.get("platformQuantity"))):null);
                dataItem.setAsin(StringUtil.valueOf(item.get("asin")));
                dataItem.setRefuntMoney(row.get("refuntMoney") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(item.get("refuntMoney")))):null);
                dataItem.setSellPriceOrigin(row.get("sellPriceOrigin") != null?BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(item.get("sellPriceOrigin")))):null);
                dataItem.setStockWarehouseId(StringUtil.valueOf(item.get("stockWarehouseId")));
                dataItem.setStockWarehouseName(StringUtil.valueOf(item.get("stockWarehouseName")));
                dataItem.setStatus(StringUtil.valueOf(item.get("status")));
                itemsList.add(dataItem);
            }
        }
        if (orderDataList.size() != 0) {
            orderDataMapper.insertList(orderDataList);
        }
        if (itemsList.size() != 0) {
            orderDataMapper.insertItemsList(itemsList);
        }

    }


    /**
     * 采购单
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 30 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void purchase() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = orderDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮purchaseData数据拉取任务");
        baseHandle("采购单", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理采购
     *
     * @param data
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void handlePurchaseData(List<Map> data) throws Exception {
        String fetureDate = DateUtil.getFetureDate(0);
        for (Map map : data) {
            CaravanPurchaseData purchaseData = new CaravanPurchaseData();
            String purchaseId = StringUtil.valueOf(map.get("purchaseId"));
            purchaseData.setDate(fetureDate);
            purchaseData.setPurchaseId(purchaseId);
            purchaseData.setCompanyId(StringUtil.valueOf(map.get("companyId")));
            purchaseData.setGroupId(StringUtil.valueOf(map.get("groupId")));
            purchaseData.setFreightSum(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("freightSum")))));
            purchaseData.setDiscountAmount(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("discountAmount")))));
            purchaseData.setTaxAmount(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("taxAmount")))));
            purchaseData.setTotalAmount(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("totalAmount")))));
            purchaseData.setPretaxTotalAmount(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("pretaxTotalAmount")))));
            purchaseData.setQuantitySum(Integer.valueOf(StringUtil.valueOf(map.get("quantitySum"))));
            purchaseData.setFlag(StringUtil.valueOf(map.get("flag")));
            purchaseData.setFlagDesc(StringUtil.valueOf(map.get("flagDesc")));
            purchaseData.setNoWarehousing(Integer.valueOf(StringUtil.valueOf(map.get("noWarehousing"))));
            purchaseData.setProviderId(StringUtil.valueOf(map.get("providerId")));
            purchaseData.setProviderName(StringUtil.valueOf(map.get("providerName")));
            purchaseData.setTargetWarehouseId(StringUtil.valueOf(map.get("targetWarehouseId")));
            purchaseData.setTargetWarehouseName(StringUtil.valueOf(map.get("targetWarehouseName")));
            purchaseData.setContent(StringUtil.valueOf(map.get("content")));
            purchaseData.setCreateOperId(StringUtil.valueOf(map.get("createOperId")));
            purchaseData.setCreateOperName(StringUtil.valueOf(map.get("createOperName")));
            purchaseData.setCreateTime(StringUtil.valueOf(map.get("createTime")));
            purchaseData.setUpdateTime(StringUtil.valueOf(map.get("updateTime")));
            purchaseData.setAli1688SumPayment(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("ali1688SumPayment")))));
            purchaseData.setLastStorageTime(StringUtil.valueOf(map.get("lastStorageTime")));
            purchaseData.setBuyerId(StringUtil.valueOf(map.get("buyerId")));
            purchaseData.setBuyerName(StringUtil.valueOf(map.get("buyerName")));
            purchaseData.setHandleStatus(0);
            //先判断当前的采购单是否存在
            insertOrUpdatePurchaseData(purchaseId,purchaseData);

            //如果没有item，执行下一条数据
            if (null == map.get("item")) {
                continue;
            }
            //先删除之前该采购单所有相关的item数据
            purchaseDataMapper.deletePurchaseDataItemByPurchaseId(purchaseId);
            //item列表
            List<CaravanPurchaseDataItem> itemsList = new ArrayList<>();
            List<Map> items = JSONArray.parseArray(StringUtil.valueOf(map.get("item")), Map.class);
            for (Map item : items) {
                CaravanPurchaseDataItem dataItem = new CaravanPurchaseDataItem();
                dataItem.setPurchaseId(purchaseId);
                dataItem.setDate(fetureDate);
                dataItem.setStockId(StringUtil.valueOf(item.get("stockId")));
                dataItem.setStockSku(StringUtil.valueOf(item.get("stockSku")));
                dataItem.setStockSkuNameCn(StringUtil.valueOf(item.get("stockSkuNameCn")));
                dataItem.setPurchaseNum(ToolUtil.valueOfInteger(StringUtil.valueOf(item.get("purchaseNum"))));
                dataItem.setEnterWarehouseNum(ToolUtil.valueOfInteger(StringUtil.valueOf(item.get("enterWarehouseNum"))));
                dataItem.setWastageNum(Integer.valueOf(StringUtil.valueOf(item.get("wastageNum"))));
                dataItem.setSellPrice(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(item.get("sellPrice")))));
                dataItem.setRemark(StringUtil.valueOf(item.get("remark")));
                dataItem.setExpressMoney(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(item.get("expressMoney")))));
                dataItem.setBuyerId(StringUtil.valueOf(item.get("buyerId")));
                dataItem.setBuyerName(StringUtil.valueOf(item.get("buyerName")));
                dataItem.setPretaxUnitPrice(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(item.get("pretaxUnitPrice")))));
                dataItem.setPretaxEnterWarehouseValue(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(item.get("pretaxEnterWarehousValue")))));
                dataItem.setIsDelete(StringUtil.valueOf(item.get("isDelete")));
                itemsList.add(dataItem);
            }
            //新增对应的items
            if (itemsList.size() != 0) {
                purchaseDataMapper.insertItemsList(itemsList);
            }
        }
    }


    /**
     * 库存查询
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 35 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void inventoryQuery() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = stockWarehouseDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮stockWarehouseData数据拉取任务");
        baseHandle("库存查询", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理库存查询
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleStockWarehouseData(List<Map> data) throws Exception {
        List<CaravanStockWarehouseData> list = new ArrayList<>(data.size());
        String fetureDate = DateUtil.getFetureDate(0);
        for (Map map : data) {
            CaravanStockWarehouseData warehouseData = new CaravanStockWarehouseData();
            warehouseData.setDate(fetureDate);
            String stockId = StringUtil.valueOf(map.get("stockId"));
            String wearhouseId = StringUtil.valueOf(map.get("wearhouseId"));
            warehouseData.setCompanyId(StringUtil.valueOf(map.get("companyId")));
            warehouseData.setStockId(stockId);
            warehouseData.setStockSku(StringUtil.valueOf(map.get("stockSku")));
            warehouseData.setStockName(StringUtil.valueOf(map.get("stockName")));
            warehouseData.setWearhouseId(wearhouseId);
            warehouseData.setWarhouseName(StringUtil.valueOf(map.get("warhouseName")));
            warehouseData.setStockQuantity(Integer.valueOf(StringUtil.valueOf(map.get("stockQuantity"))));
            warehouseData.setShippingQuantity(Integer.valueOf(StringUtil.valueOf(map.get("shippingQuantity"))));
            warehouseData.setDefaultCost(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(map.get("defaultCost")))));
            warehouseData.setTotalValue(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(map.get("totalValue")))));
            warehouseData.setLastDepotTime(StringUtil.valueOf(map.get("lastDepotTime")));
            warehouseData.setLastStorageTime(StringUtil.valueOf(map.get("lastStorageTime")));
            warehouseData.setCreateTime(StringUtil.valueOf(map.get("createTime")));
            insertOrUpdateStockWarehouseData(stockId,wearhouseId,warehouseData);
        }
    }


    /**
     * 商品查询
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 40 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void stockData() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = stockDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮stockData数据拉取任务");
        baseHandle("商品查询", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理商品查询
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleStock(List<Map> data) throws Exception {
        List<CaravanStockData> list = new ArrayList<>(data.size());
        String fetureDate = DateUtil.getFetureDate(0);
        for (Map map : data) {
            CaravanStockData stockData = new CaravanStockData();
            stockData.setDate(fetureDate);
            String stockId = StringUtil.valueOf(map.get("stockId"));
            stockData.setCompanyId(StringUtil.valueOf(map.get("companyId")));
            stockData.setStockId(stockId);
            stockData.setStockSku(StringUtil.valueOf(map.get("stockSku")));
            stockData.setStockSkuNameCn(StringUtil.valueOf(map.get("stockSkuNameCn")));
            stockData.setParentCategoryId(StringUtil.valueOf(map.get("parentCategoryId")));
            stockData.setParentCategoryNameCn(StringUtil.valueOf(map.get("parentCategoryNameCn")));
            stockData.setCategoryId(StringUtil.valueOf(map.get("categoryId")));
            stockData.setParentCategoryNameCn(StringUtil.valueOf(map.get("categoryNameCn")));
            stockData.setDeclareValue(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(map.get("declareValue")))));
            stockData.setPurchaseId(StringUtil.valueOf(map.get("purchaseId")));
            stockData.setPurchaseName(StringUtil.valueOf(map.get("purchaseName")));
            stockData.setDeveloperId(StringUtil.valueOf(map.get("developerId")));
            stockData.setDeveloperName(StringUtil.valueOf(map.get("developerName")));
            stockData.setArtDesignerId(StringUtil.valueOf(map.get("artDesignerId")));
            stockData.setArtDesignerName(StringUtil.valueOf(map.get("artDesignerName")));
            stockData.setWeight(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("weight")))));
            stockData.setPackageCount(Integer.parseInt(StringUtil.valueOf(map.get("packageCount"))));
            stockData.setPurchasePrice(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(map.get("purchasePrice")))));
            stockData.setVirtualSku(StringUtil.valueOf(map.get("virtualSku")));
            stockData.setLength(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("length")))));
            stockData.setWidth(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("width")))));
            stockData.setHeight(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("height")))));
            stockData.setVolumeWeight(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(map.get("volumeWeight")))));
            stockData.setSkuTimeCreated(StringUtil.valueOf(map.get("skuTimeCreated")));
            stockData.setSkuTimeUpdate(StringUtil.valueOf(map.get("skuTimeUpdate")));
            stockData.setRetailId(StringUtil.valueOf(map.get("retailId")));
            stockData.setRetailName(StringUtil.valueOf(map.get("retailName")));
            stockData.setStockName(StringUtil.valueOf(map.get("stockName")));
            stockData.setPackageId(StringUtil.valueOf(map.get("packageId")));
            stockData.setPackageName(StringUtil.valueOf(map.get("packageName")));
            stockData.setStatus(StringUtil.valueOf(map.get("status")));
            stockData.setStatusDesc(StringUtil.valueOf(map.get("statusdesc")));
            stockData.setStockPicture(StringUtil.valueOf(map.get("stockPicture")));
            insertOrUpdateStockData(stockId,stockData);
        }
    }


    /**
     * 出入库流水
     * 每天24:00需更新一次，并添加更新日期保存
     */
    @Scheduled(cron = "0 45 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void storageLogData() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = storageLogDataMapper.getLatestDate();
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)){
            startTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,0,0,0);
        }else {
            startTime = LocalDateTime.parse(latestDate,df);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(),nowTime.getMonthValue(),nowTime.getDayOfMonth()-2,23,59,59);
        log.info("开始" + startTime + "到" + endTime + "的马帮storageLogData数据拉取任务");
        baseHandle("出入库流水", startTime.format(df), endTime.format(df));
    }

    /**
     * 处理出入库流水
     *
     * @param lists
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleStorageLogData(List<Map> lists) throws Exception {
        List<CaravanStorageLogData> insertList = new ArrayList<>(lists.size());
        String date = DateUtil.getNowDateTime();
        for (Map row : lists) {
            CaravanStorageLogData data = new CaravanStorageLogData();
            data.setDate(date);
            String logId = StringUtil.valueOf(row.get("id"));
            data.setLogId(logId);
            data.setCompanyId(StringUtil.valueOf(row.get("companyId")));
            data.setStockId(StringUtil.valueOf(row.get("stockId")));
            data.setStockSku(StringUtil.valueOf(row.get("stockSKu")));
            data.setStockSkuName(StringUtil.valueOf(row.get("stockSkuName")));
            data.setWearhouseId(StringUtil.valueOf(row.get("wearhouseId")));
            data.setWearhouseName(StringUtil.valueOf(row.get("wearhouseName")));
            data.setCtype(StringUtil.valueOf(row.get("ctype")));
            data.setQuantityAfter(Integer.valueOf(StringUtil.valueOf(row.get("quantityAfter"))));
            data.setQuantity(Integer.valueOf(StringUtil.valueOf(row.get("quantity"))));
            if (null != row.get("price")) {
                data.setPrice(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("price")))));
            }
            data.setPriceSum(BigDecimal.valueOf(Double.valueOf(StringUtil.valueOf(row.get("pricesum")))));
            data.setOperId(StringUtil.valueOf(row.get("operId")));
            data.setOperName(StringUtil.valueOf(row.get("operName")));
            data.setDocumentNum(StringUtil.valueOf(row.get("documentNum")));
            String documentType = StringUtil.valueOf(row.get("documentType"));
            String remark = StringUtil.valueOf(row.get("remark"));
            if ("".equals(documentType) || null == documentType) {
                //将备注中的HTML标签去除
                // <p>段落替换为换行
                documentType = remark.replaceAll("<p .*?>", "");
                // <br><br/>替换为换行
                documentType = documentType.replaceAll("<br\\s*/?>", "");
                // 去掉其它的<>之间的东西
                documentType = documentType.replaceAll("\\<.*?>", "");
                //去掉其他的[]之间的东西
                documentType = documentType.replaceAll("\\[.*?]", "");
                // 去掉空格
                documentType = documentType.replaceAll(" ", "");
            }
            data.setDocumentType(documentType);
            if (documentType.equals("退货单验货入库")){
                String documentNum = remark.replaceAll("\\[","");
                int idx = documentNum.indexOf("]");
                documentNum = documentNum.substring(0, idx);
                data.setDocumentNum(documentNum);
            }
            data.setRemark(remark);
            data.setTimeCreate(StringUtil.valueOf(row.get("timecreate")));
            data.setCreateDateTime(StringUtil.valueOf(row.get("createDateTime")));
            data.setHandleStatus(0);
            //判断数据是否存在
            CaravanStorageLogData oneInfo = storageLogDataMapper.getOneInfoByLogId(logId);
            if (null == oneInfo) {
                data.setId(null);
                insertList.add(data);
//                storageLogDataMapper.insert(data);
            }
        }
        if (insertList.size() != 0) {
           storageLogDataMapper.insertList(insertList);
        }
    }


    /*
    以下为各个表进数据库的事务处理方法
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    Integer insertBaseSkuInfo(String sellerId,String area,String msku,String fetureDate){
        BaseSkuInfoDTO baseSkuInfoDTO = new BaseSkuInfoDTO();
        baseSkuInfoDTO.setSellerId(sellerId);
        baseSkuInfoDTO.setArea(area);
        baseSkuInfoDTO.setSku(msku);
        baseSkuInfoDTO.setParentSku("");
        baseSkuInfoDTO.setCategory("");
        baseSkuInfoDTO.setAddUser("sujiandong");
        baseSkuInfoDTO.setAddTime(fetureDate);
        baseSkuInfoDTO.setModUser("sujiandong");
        baseSkuInfoDTO.setModTime(fetureDate);
        iBaseSkuInfoMapper.insert(baseSkuInfoDTO);
        return iBaseSkuInfoMapper.getIdByMskuAndSellerIdAndArea(msku, sellerId, area);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void insertErpSku(Integer mskuId,String stockSku,String fetureDate){
        BaseSkuInfoDTO oneInfoBySkuAndErpSku = iBaseErpskuSkuRelationMapper.getOneInfoBySkuAndErpSku(mskuId, stockSku);
        if (oneInfoBySkuAndErpSku == null){
            BaseErpskuSkuRelationDTO baseErpskuSkuRelationDTO = new BaseErpskuSkuRelationDTO();
            baseErpskuSkuRelationDTO.setErpsku(stockSku);
            baseErpskuSkuRelationDTO.setSku(mskuId);
            baseErpskuSkuRelationDTO.setAddUser("sujiandong");
            baseErpskuSkuRelationDTO.setAddTime(fetureDate);
            baseErpskuSkuRelationDTO.setModUser("sujiandong");
            baseErpskuSkuRelationDTO.setModTime(fetureDate);
            iBaseErpskuSkuRelationMapper.insert(baseErpskuSkuRelationDTO);
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void insertOrUpdateBillsData(String orderNum,CaravanBillsData data){
        //先判断该账单是否已经存在
        CaravanBillsData oneInfoCaravanBillsDataDO = billsDataMapper.getOneInfoByOrderNum(orderNum);
        if (null != oneInfoCaravanBillsDataDO && null != oneInfoCaravanBillsDataDO.getId()) {
            data.setId(oneInfoCaravanBillsDataDO.getId());
            baseUpdate(data);
        } else {
            data.setId(null);
            baseInsert(data);
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void insertOrUpdateMskuData(String shops,String msku,String amazonsite,CaravanMskuData mskuData){
        CaravanMskuData oneInfo = mskuDataMapper.getOneInfoByShopsAndMskuAndAmazonsite(shops, msku, amazonsite);
        if (null != oneInfo && null != oneInfo.getId()) {
            mskuData.setId(oneInfo.getId());
            baseUpdate(mskuData);
        } else {
            mskuData.setId(null);
            baseInsert(mskuData);
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void insertOrUpdateMskuShippbatchData(String shippNo,Map map){
        //调拨shippNo判断是否添加过
        CaravanMskuShippbatchData mskuShippbatchData = mskuShippbatchDataMapper.getMskuShippbatchDataByShippNo(shippNo);
        if (mskuShippbatchData == null) {  //添加
            mskuShippbatchData = new CaravanMskuShippbatchData();
            mskuShippbatchData.setCompanyId(StringUtil.valueOf(map.get("companyId")));
            mskuShippbatchData.setShippNo(shippNo);
            mskuShippbatchData.setShippName(StringUtil.valueOf(map.get("shippName")));
            mskuShippbatchData.setStatus(StringUtil.valueOf(map.get("status")));
            mskuShippbatchData.setFbaWarhouseId(StringUtil.valueOf(map.get("fbawarhouseId")));
            mskuShippbatchData.setFbaWarhouse(StringUtil.valueOf(map.get("fbawarhouse")));
            mskuShippbatchData.setWarehouse(StringUtil.valueOf(map.get("warehouse")));
            mskuShippbatchData.setWarehouseId(StringUtil.valueOf(map.get("warehouseId")));
            mskuShippbatchData.setCountryCode(StringUtil.valueOf(map.get("countryCode")));
            mskuShippbatchData.setExpressTime(StringUtil.valueOf(map.get("expressTime")));
            mskuShippbatchData.setTimeCreate(StringUtil.valueOf(map.get("timeCreate")));
            mskuShippbatchData.setTimeUpdate(StringUtil.valueOf(map.get("timeUpdate")));
            mskuShippbatchDataMapper.insert(mskuShippbatchData);

        } else {//修改
            mskuShippbatchData.setCompanyId(StringUtil.valueOf(map.get("companyId")));
            mskuShippbatchData.setShippNo(shippNo);
            mskuShippbatchData.setShippName(StringUtil.valueOf(map.get("shippName")));
            mskuShippbatchData.setStatus(StringUtil.valueOf(map.get("status")));
            mskuShippbatchData.setFbaWarhouseId(StringUtil.valueOf(map.get("fbawarhouseId")));
            mskuShippbatchData.setFbaWarhouse(StringUtil.valueOf(map.get("fbawarhouse")));
            mskuShippbatchData.setWarehouse(StringUtil.valueOf(map.get("warehouse")));
            mskuShippbatchData.setWarehouseId(StringUtil.valueOf(map.get("warehouseId")));
            mskuShippbatchData.setCountryCode(StringUtil.valueOf(map.get("countryCode")));
            mskuShippbatchData.setExpressTime(StringUtil.valueOf(map.get("expressTime")));
            mskuShippbatchData.setTimeCreate(StringUtil.valueOf(map.get("timeCreate")));
            mskuShippbatchData.setTimeUpdate(StringUtil.valueOf(map.get("timeUpdate")));
            baseUpdate(mskuShippbatchData);
        }

        if (map.get("item") != null) {
            //删除该调拨批次所有的item数据，重新插入
            mskuShippbatchDataMapper.delMskuShippbatchDataItem(shippNo);
            String itemStr = map.get("item").toString();
            List<Map> itemArray = JSONArray.parseArray(itemStr, Map.class);
            for (Map itemMap : itemArray) {
                CaravanMskuShippbatchDataItem mskuShippbatchDataItem = new CaravanMskuShippbatchDataItem();
                String platformSku = (String) itemMap.get("platformSku");
                mskuShippbatchDataItem.setShippNo(shippNo);
                mskuShippbatchDataItem.setPlatformSku(platformSku);
                mskuShippbatchDataItem.setFbaStockId(StringUtil.valueOf(itemMap.get("fbaStockId")));
                mskuShippbatchDataItem.setShippedQuantity(Integer.parseInt(StringUtil.valueOf(itemMap.get("shippedQuantity"))));
                mskuShippbatchDataItem.setReceivedQuantity(Integer.parseInt(StringUtil.valueOf(itemMap.get("receivedQuantity"))));
                mskuShippbatchDataItem.setDelieverQuantity(Integer.parseInt(StringUtil.valueOf(itemMap.get("deliveryQuantity"))));
                mskuShippbatchDataItem.setApplyQuantity(Integer.parseInt(StringUtil.valueOf(itemMap.get("applyQuantity"))));
                mskuShippbatchDataMapper.insertItem(mskuShippbatchDataItem);
            }
        }

        if (map.get("pack") != null) {
            //删除该调拨批次所有的pack数据，重新插入
            mskuShippbatchDataMapper.delMskuShippbatchDataPack(shippNo);
            String itemStr = map.get("pack").toString();
            List<Map> packArray = JSONArray.parseArray(itemStr, Map.class);
            for (Map packMap : packArray) {
                CaravanMskuShippbatchDataPack mskuShippbatchDataPack = new CaravanMskuShippbatchDataPack();
                String packNo = StringUtil.valueOf(packMap.get("packNo"));
                mskuShippbatchDataPack.setShippNo(shippNo);
                mskuShippbatchDataPack.setPackNo(packNo);
                mskuShippbatchDataPack.setLength(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(packMap.get("length")))));
                mskuShippbatchDataPack.setWidth(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(packMap.get("width")))));
                mskuShippbatchDataPack.setHeight(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(packMap.get("height")))));
                mskuShippbatchDataPack.setWeight(BigDecimal.valueOf(Double.parseDouble(StringUtil.valueOf(packMap.get("weight")))));
                //mskuShippbatchDataPack.setSkuInfo(StringUtil.valueOf(packMap.get("skuInfo")));
                //把skuinfo的数据也转为json对象并存入新的关系表中
                if (packMap.get("skuInfo") != null && !"".equals(StringUtil.valueOf(packMap.get("skuInfo")))) {
                    //System.out.println(StringUtil.valueOf(packMap.get("skuInfo")));
                    String skuInfo = StringUtil.valueOf(packMap.get("skuInfo"));
                    List<Map> skuInfoMap = JSONArray.parseArray(skuInfo, Map.class);
                    List<CaravanMskuShippbatchDataPackItem> mskuShippbatchDataPackItemList = new ArrayList<>();
                    mskuShippbatchDataPackItemMapper.delPackItem(shippNo, packNo);
                    for (Map skuInfoItem : skuInfoMap) {
                        CaravanMskuShippbatchDataPackItem mskuShippbatchDataPackItem = new CaravanMskuShippbatchDataPackItem();
                        mskuShippbatchDataPackItem.setShippNo(shippNo);
                        mskuShippbatchDataPackItem.setPackNo(packNo);
                        mskuShippbatchDataPackItem.setFbaStockId(StringUtil.valueOf(skuInfoItem.get("fbastockId")));
                        mskuShippbatchDataPackItem.setDelieverQuantity(Integer.parseInt(StringUtil.valueOf(skuInfoItem.get("delieverQuantity"))));
                        mskuShippbatchDataPackItemList.add(mskuShippbatchDataPackItem);
                    }
                    mskuShippbatchDataPackItemMapper.insertList(mskuShippbatchDataPackItemList);
                }
                mskuShippbatchDataMapper.insertMskuShippbatchPack(mskuShippbatchDataPack);
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void insertOrUpdatePurchaseData(String purchaseId,CaravanPurchaseData purchaseData){
        CaravanPurchaseData oneInfoByPurchaseId = purchaseDataMapper.getOneInfoByPurchaseId(purchaseId);
        if (null != oneInfoByPurchaseId && null != oneInfoByPurchaseId.getId()) {
            Long id = oneInfoByPurchaseId.getId();
            purchaseData.setId(id);
            baseUpdate(purchaseData);
        } else {
            purchaseData.setId(null);
            baseInsert(purchaseData);
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void insertOrUpdateStockWarehouseData(String stockId,String wearhouseId,CaravanStockWarehouseData warehouseData){
        CaravanStockWarehouseData oneInfo = stockWarehouseDataMapper.getOneInfoByStockIdAndWearhouseId(stockId, wearhouseId);
        if (null != oneInfo && null != oneInfo.getId()) {
            warehouseData.setId(oneInfo.getId());
            baseUpdate(warehouseData);
        } else {
            warehouseData.setId(null);
            baseInsert(warehouseData);
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    void insertOrUpdateStockData(String stockId,CaravanStockData stockData){
        //先判断是否存在这个商品id
        CaravanStockData oneInfoByStockId = stockDataMapper.getOneInfoByStockId(stockId);
        if (null != oneInfoByStockId && null != oneInfoByStockId.getId()) {
            stockData.setId(oneInfoByStockId.getId());
            baseUpdate(stockData);
        } else {
            stockData.setId(null);
            baseInsert(stockData);
        }
    }


}
